package gl.android.jxzs.socket;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;

public class Client {
	private Socket socketClient;
	private DataOutputStream dos;
	private DataInputStream dis;
	private int timeout = 10 * 1000;
	private MessageReceiver mMessageReceiver;
	private MessageSender mMessageSender;
	private MessageHandler mMessageHandler = new MessageHandler() {
		public void handle(String content) {
			if (content == null) {
				System.out.println("packet is null");
				return;
			}
			System.out.println("receive:" + content);
		};
	};

	public MessageHandler getMessageHandler() {
		return mMessageHandler;
	}

	public void setMessageHandler(MessageHandler mMessageHandler) {
		this.mMessageHandler = mMessageHandler;
	}

	/**
	 * 
	 * @param ip
	 *            server ip
	 * @param port
	 *            server port
	 * @param sn
	 *            gateway searilnumber
	 * @throws UnknownHostException
	 * @throws IOException
	 */
	public void connect(String ip, int port) throws UnknownHostException,
			IOException {
		disConnect();
		socketClient = new Socket();
		socketClient.connect(new InetSocketAddress(ip, port), timeout);
		dos = new DataOutputStream(socketClient.getOutputStream());
		dis = new DataInputStream(socketClient.getInputStream());

		mMessageSender = new MessageSender(dos);
		mMessageReceiver = new MessageReceiver(dis);
		mMessageReceiver.addMessageHandler(mMessageHandler);
	}

	public void disConnect() {
		try {
			if (dos != null) {
				dos.close();
			}
			if (dis != null) {
				dis.close();
			}
			if (mMessageReceiver != null) {
				mMessageReceiver.close();
			}
			if (socketClient != null && !socketClient.isClosed()) {
				socketClient.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void sendMessage(String joString) {
		mMessageSender.send(joString.getBytes());
	}

	public static void main(String[] args) {
		Client client = new Client();
		try {
			client.connect("120.198.105.94", 65011);
			client.sendMessage("002101000113902210392");
			client.sendMessage("0078040001123446590aa597149386997520141017122146");
			client.sendMessage("0078040001123446");
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
